<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片部分 -->
    <el-card>
      <!-- 提示部分alert -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 进度条 -->
      <el-steps
        :active="+active"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- left Tabs切换 -->
      <el-form
        :model="infoForm"
        :rules="infoRules"
        ref="infoRef"
        label-position="top"
      >
        <el-tabs
          tabPosition="left"
          v-model="active"
          :before-leave="tabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane
            label="基本信息"
            name="0"
          >
            <el-form-item
              label="商品名称"
              prop="goods_name"
            >
              <el-input v-model="infoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item
              label="商品价格"
              prop="goods_price"
            >
              <el-input v-model="infoForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item
              label="商品重量"
              prop="goods_weight"
            >
              <el-input v-model="infoForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item
              label="商品数量"
              prop="goods_number"
            >
              <el-input v-model="infoForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item
              label="商品分类"
              prop="goods_cat"
            >
              <el-cascader
                v-model="infoForm.goods_cat"
                :options="dataList"
                :props="sortProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品参数"
            name="1"
          >
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyList"
              :key="item.attr_id"
            >
              <el-checkbox-group
                v-model="item.attr_vals"
                border
              >
                <el-checkbox
                  class="checkbox-item"
                  :label="it"
                  v-for="(it,i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品属性"
            name="2"
          >
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyList"
              :key="item.attr_id"
            >
              <el-checkbox-group
                v-model="item.attr_vals"
                border
              >
                <el-checkbox
                  class="checkbox-item"
                  :label="it"
                  v-for="(it,i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品图片"
            name="3"
          >
            <el-upload
              :action="activeUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane
            label="商品内容"
            name="4"
          >
          <!-- 富文本编辑 -->
            <quill-editor
              v-model="infoForm.goods_introduce"
            >
            </quill-editor>
            <el-button class="quill-btn" type="primary" @click="addShop">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 展示图片 -->
    <el-dialog
      title="提示"
      :visible.sync="isshowPic"
      width="50%"
      :lock-scroll="false"
    >
      <img
        class="pic"
        :src="showPic"
        alt=""
      >
    </el-dialog>
  </div>
</template>
<script>
import { getData ,setData} from "network/goodsList";
import _ from 'lodash'

export default {
  data() {
    return {
      active: 0,
      infoForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_introduce : '',
        goods_cat : [],
        pics: [],
        attrs : []
      },
      infoRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" }
        ]
      },
      dataList: [],
      value: [],
      sortProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },

      manyList: [],
      onlyList: [],

      activeUrl: "http://timemeetyou.com:8889/api/private/v1/upload",
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      showPic: "",
      isshowPic: false
    };
  },
  methods: {
    // 获取分类数据
    getData() {
      getData("categories").then(res => {
        if (res.data.meta.status === 200) {
          this.dataList = res.data.data;
        }
      });
    },
    handleChange() {
      // console.log(this.infoForm.goods_cat)
      if (this.infoForm.goods_cat.length !== 3) {
        this.infoForm.goods_cat = [];
      }
    },
    tabLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.infoForm.goods_cat.length !== 3) {
        this.$Message.error("请选择商品分类！");
        return false;
      }
    },
    tabClick() {
      if (this.active === "1") {
        getData(`categories/${this.id}/attributes`, { sel: "many" }).then(
          res => {
            if (res.data.meta.status === 200) {
              res.data.data.forEach(item => {
                item.attr_vals =
                  item.attr_vals.length !== 0 ? item.attr_vals.split(" ") : [];
              });
              this.manyList = res.data.data;
            }
          }
        );
      }
      if (this.active === "2") {
        getData(`categories/${this.id}/attributes`, { sel: "only" }).then(
          res => {
            console.log(res);
            if (res.data.meta.status === 200) {
              res.data.data.forEach(item => {
                item.attr_vals =
                  item.attr_vals.length !== 0 ? item.attr_vals.split(" ") : [];
              });
              this.onlyList = res.data.data;
              console.log(this.onlyList);
            }
          }
        );
      }
    },
    // 点击查看
    handlePreview(file) {
      // console.log(file);
      this.isshowPic = true;
      this.showPic = file.response.data.url;
      console.log(this.showPic);
    },
    // 点击删除
    handleRemove(file) {
      const index = this.infoForm.pics.findIndex(item => {
        return file.response.data.tmp_path === item.pic;
      });
      this.infoForm.pics.splice(index, 1);
      // console.log(this.infoForm.pics)
    },
    // 上传成功
    handleSuccess(response) {
      const obj = { pic: response.data.tmp_path };
      this.infoForm.pics.push(obj);
    },
    addShop(){
      this.$refs.infoRef.validate(valid => {
        if(!valid){
          this.$Message.error('请填写必要的表单项！')
        }
        const from = _.cloneDeep(this.infoForm)
        from.goods_cat = from.goods_cat.join(',')

        this.manyList.forEach(item => {
          const obj = {
            attr_id : item.attr_id,
            attr_value : item.attr_value
          }
          from.attrs.push(obj)
        })
        this.onlyList.forEach(item => {
          const obj = {
            attr_id : item.attr_id,
            attr_value : item.attr_vals.join(' ')
          }
          from.attrs.push(obj)
        })

        setData('/goods',from).then(res => {
          console.log(res)
          if(res.data.meta.status === 201){
            this.$Message.success(res.data.meta.msg)
            this.$router.push('/goods')
          }else{
            this.$Message.error(res.data.meta.msg)
          }
        })
        // console.log(from)
      })
    }
  },
  computed: {
    id() {
      return this.infoForm.goods_cat[2];
    }
  },
  created() {
    this.getData();
  }
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  padding-bottom: 20px;
}
.el-steps--horizontal {
  margin-top: 15px;
}
.el-tabs {
  margin-top: 15px;
}
.checkbox-item {
  margin: 0 0 0 5px !important;
}
.pic {
  width: 100%;
}
.quill-btn{
  margin-top: 15px;
}
</style>